/*    
    This file is part of AWC2.

    AWC2 is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    AWC2 is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with AWC2.  If not, see <http://www.gnu.org/licenses/>.
*/
    
localStorage["blacklist"] = "";
localStorage["unblocked"] = "";
localStorage["rate"] = "";
var examined = [];

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
        
        
        var url = details.url;
        
        //console.log("Entro webrequest."+url);
        
        // ignore POST request
        if(details.method == 'POST') return { cancel: false };
        
        var blocked = localStorage.blacklist;
        blocked = (blocked ? blocked.split(",") : []);
        
        var unblocked = localStorage.unblocked;
        unblocked = (unblocked ? unblocked.split(",") : []);
        
        if(unblocked.lenght != 0) {
            for( id in unblocked) {
                if(url.indexOf(unblocked[id]) != -1) {
                    //console.log("SBlocco url: "+url);
                    chrome.tabs.getSelected(null, function(tab) {
                        tab = tab.id;
                        chrome.pageAction.show(tab);
                    });
                    
                    return { cancel: false };
                }
            }
        }
        
        // if this url is in blocked array stop it
        if(blocked.lenght != 0) {
            for( id in blocked) {
                if(url.indexOf(blocked[id]) != -1) {
                    //////console.log("Blocco url: "+url);
                    chrome.tabs.getSelected(null, function(tab) {
                        tab = tab.id;
                        chrome.pageAction.show(tab);
                    });
                    return { cancel: true };
                }
            }
        }

        
        if(examined.lenght != 0) {
            for( id in examined) {
                if(url.indexOf(examined[id]) != -1) {
                    //console.log("NON blocco url: "+url);
                    return { cancel: false };
                }
            }
        }
        
        //console.log("Inizio il check.");
        examined.push(url);
        ws.startCheck(url);
        //console.log("Blacklist attuale:"+localStorage.blacklist);
        
        return { cancel: false };
    },
    {urls: ["<all_urls>"]},
    ["blocking"]
);


var ws = {
    getDomain: function (url) {
        
        var regex1 = new RegExp(/[^:]*(:\/\/)?([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})(:[0-9]+)?\/?.*/gmi);
        var match = regex1.exec(url);
        
        if(match) {
            
            console.log("Dominio: "+match);
            return "://"+match[2]+"/";
        }
        
        var regex = new RegExp(/[^:]*(:\/\/)?([^.]*[\.]?[^.]+[\.][^\/]+).*/gmi);
        
        match = regex.exec(url);
        
        if(match) {
            
            //console.log("Dominio: "+match[2]);
            return "://"+match[2]+"/";
        }
    },
    getPage: function (url, callback) {
        
        var xhr = new XMLHttpRequest();

        xhr.open('GET', url, true);
    
        xhr.onerror = function() {
            document.documentElement.innerHTML = 'Error getting Page';
        }
        
        
        
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status != 200)    
                    response = xhr.status;
                else
                    response = xhr.responseText;

                callback(response);
                
            }
        }
        
        
        xhr.send(null);
        //return response;
    },
    
    
    checkScript: function (response) {
        var blackList = [];
        var domain;
        var regex = new RegExp(/<!-- Reliability: ([0-9]\.[0-9]) --><script[^>]*src[^>]*=[^>]*[\"']([^>\"']*)[\"'][^>]*>[^>]*\/script[^>]*><!-- end -->/gmi);
        var match = regex.exec(response);
        
        while(match != null) {
            //console.log("Match!");
            
            domain = ws.getDomain(match[2]);
            blackList.push(domain+"|"+match[1]);
            
            //console.log("Ho inserito "+domain);
            
            match = regex.exec(response);
        }
        updateBlacklist(blackList);
        //if(localStorage.blacklist) chrome.extension.sendMessage({text: localStorage.blacklist}, function(response) {console.log(response.rs);});
        //console.log("Esco");
    },
    checkIframe: function (response) {
        var blackList = [];
        var regex = new RegExp(/<!-- Reliability: ([0-9]\.[0-9]) --><iframe[^>]*src[^>]*=[^>]*[\"']([^>\"']*)[\"'][^>]*>[^>]*\/iframe[^>]*><!-- end -->/gmi);
        var match = regex.exec(response);
        
        while(match != null) {
            //console.log("Match!");
            
            domain = ws.getDomain(match[2]);
            blackList.push(domain+"|"+match[1]);
            
            //console.log("Ho inserito "+domain);
            
            match = regex.exec(response);
        }
        updateBlacklist(blackList);
        //console.log("Esco");
    },
    checkApplet: function (response) {
        var blackList = [];
        var regex = new RegExp(/<!-- Reliability: ([0-9]\.[0-9]) --><applet[^>]*codebase=[^>"']*["']([^>"']+)["'][^>]*>.*\/applet[^>]*><!-- end -->/gmi);
        var match = regex.exec(response);
        while(match != null) {
            //console.log("Match!");
            
            domain = ws.getDomain(match[2]);
            blackList.push(domain+"|"+match[1]);
            
            //console.log("Ho inserito "+domain);
            
            match = regex.exec(response);
        }
        updateBlacklist(blackList);
        //if(localStorage.blacklist) chrome.extension.sendMessage({text: localStorage.blacklist}, function(response) {console.log(response.rs);});
        //console.log("Esco");
    },
    checkObject: function (response) {
        var blackList = [];
        var regex = new RegExp(/<!-- Reliability: ([0-9]\.[0-9]) --><object[^>]*data[^>]*=[^>]*["']([^>"']*)["'][^>]*>.*\/object[^>]*><!-- end -->/gmi);
        var match = regex.exec(response);
        while(match != null) {
            //console.log("Match!");
            
            domain = ws.getDomain(match[2]);
            blackList.push(domain+"|"+match[1]);
            
            //console.log("Ho inserito "+domain);
            
            match = regex.exec(response);
        }
        updateBlacklist(blackList);
        //if(localStorage.blacklist) chrome.extension.sendMessage({text: localStorage.blacklist}, function(response) {console.log(response.rs);});
        //console.log("Esco");
    },
    checkImg: function (response) {
        var blackList = [];
        var regex = new RegExp(/<!-- Reliability: ([0-9]\.[0-9]) --><img[^>]*src[^>="']*=[^>"']*["']([^>"']+)["'][^>]*><!-- end -->/gmi);
        var match = regex.exec(response);
        while(match != null) {
            //console.log("Match!");
            
            domain = ws.getDomain(match[2]);
            blackList.push(domain+"|"+match[1]);
            
            //console.log("Ho inserito "+domain);
            
            match = regex.exec(response);
        }
        updateBlacklist(blackList);
        
        //if(localStorage.blacklist) chrome.extension.sendMessage({text: localStorage.blacklist}, function(response) {console.log(response.rs);});
        //console.log("Esco");
    },
    
    startCheck: function (url) {
        this.getPage(url, function(response) {
            var page = document.implementation.createHTMLDocument("");
            page.documentElement.innerHTML = response;
            
            ws.checkScript(response);
            ws.checkIframe(response);
            ws.checkApplet(response);
            ws.checkImg(response);
            ws.checkObject(response);
            
            
            
            //localStorage["checked"] = "1";
            //document.innerHTML = response;
            //window.location.reload(true);
            //reload();
        });
    }
}


function updateBlacklist(newList) {
    var tmp = localStorage.blacklist;
    tmp = (tmp ? tmp.split(",") : []);
    
    var rtmp = localStorage.rate;
    rtmp = (rtmp ? rtmp.split(",") : []);
    
    var line;
    
    for( id in newList ) {
        line = newList[id].split("|");
        if(!in_array(line[0], tmp)) {
            tmp.push(line[0]);
            rtmp.push(line[1]);
        }
    }
    localStorage.blacklist = tmp;
    localStorage.rate = rtmp;
}

function updateRate(newList) {
    /*var tmp = localStorage.rate;
    tmp = (tmp ? tmp.split(",") : []);
    
    for( id in newList ) {
        if(!in_array(newList[id], tmp)) {
            var rate = parseInt(newList[id]) * 10;
            tmp.push(rate);
        }
    }
    localStorage.rate = tmp;*/
}

//console.log("Dump unblocked: "+ localStorage.unblocked);

function in_array(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) {
            return true;
        }
    }
    return false;
}


chrome.extension.onMessage.addListener(

    function(request, sender, sendResponse) {
        // Unblock a domain
        if(request.dominio != undefined && request.action == 'remove') {
            
            
            
            var unblocked = localStorage.unblocked;
            unblocked = (unblocked ? unblocked.split(",") : []);
            var urlclean = request.dominio;
            //urlclean = urlclean.substr(1);
            //urlclean = urlclean.slice(0, -1);
            
            if(in_array(urlclean, unblocked)) return;
            
            unblocked.push(urlclean);
            
            
            localStorage['unblocked'] = unblocked;
            //console.log("localStorage.unblocked = "+localStorage.unblocked);
            
            //console.log("Eliminato "+request.dominio+" dalla blacklist e inserito nella lista sbloccati.");
            
            // Reload Tab
            /*chrome.tabs.getSelected(null, function(tab) {
              var code = 'reload();';
              chrome.tabs.executeScript(tab.id, {code: code});
            });*/
            
            chrome.tabs.getSelected(null, function(tab) {
                chrome.tabs.reload(tab.id);
            });
        }
        else if(request.dominio != undefined && request.action == 'add') {
            if(!localStorage.unblocked) return;
            
            var unblocked = localStorage.unblocked;
            unblocked = (unblocked ? unblocked.split(",") : []);
            var urlclean = request.dominio;
            
            var id = unblocked.indexOf(urlclean);
            if(id!=-1) unblocked.splice(id, 1);
            localStorage.unblocked = unblocked;
            //console.log("Reinserisco "+request.dominio+" nella blacklist");
            //console.log("Ho eliminato il dominio "+request.dominio+" da unblocked: "+unblocked);
            
            chrome.tabs.getSelected(null, function(tab) {
                chrome.tabs.reload(tab.id);
            });
        }
        else if (request.icon == "show")
            chrome.pageAction.show(sender.tab.id); // Show icon
        else {
            var tmp = localStorage.temp;
            tmp = (tmp ? tmp.split(",") : []);
            
            var tmp2 = request.text;
            tmp2 = ( tmp2 ? tmp2.split(",") : []);
            
            for(id in tmp2) {
                if(!in_array(tmp2[id], tmp)) {
                    //console.log("Da inserire: "+tmp2[id]+" Array: "+tmp);
                    tmp.push(tmp2[id]);
                    localStorage.temp = tmp;
                }
            }
            
            
            
            sendResponse({rs: "ricevuto"});
            
            //console.log("Inseriti "+localStorage.temp);
            
            onBeforeRequest();
            
            
        }
});
